package gis.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;
import com.supermap.android.commons.EventStatus;
import com.supermap.android.maps.CoordinateReferenceSystem;
import com.supermap.android.maps.DefaultItemizedOverlay;
import com.supermap.android.maps.LayerView;
import com.supermap.android.maps.MapView;
import com.supermap.android.maps.Overlay;
import com.supermap.android.maps.Point2D;
import com.supermap.android.maps.measure.MeasureMode;
import com.supermap.android.maps.measure.MeasureParameters;
import com.supermap.android.maps.measure.MeasureResult;
import com.supermap.android.maps.measure.MeasureService;
import com.supermap.android.maps.query.FilterParameter;
import com.supermap.android.maps.query.QueryByGeometryParameters;
import com.supermap.android.maps.query.QueryByGeometryService;
import com.supermap.android.maps.query.QueryEventListener;
import com.supermap.android.maps.query.QueryResult;
import com.supermap.android.maps.query.SpatialQueryMode;
import com.supermap.services.components.commontypes.Feature;
import com.supermap.services.components.commontypes.Geometry;
import com.supermap.services.components.commontypes.GeometryType;

import gis.utils.Coord;

public class MapShow extends Activity {
        public static  String DEFAULT_URL = "http://111.40.100.173:8090/iserver/services/map-lake/rest/maps/lakeMap";
//    public static final String DEFAULT_URL = "http://125.220.159.168:8090/iserver/services/map-lake/rest/maps/lakeMap";
    static {
    DEFAULT_URL = "http://"+MyApplication.share().getResources().getString(R.string.superMap_ip)+":8090/iserver/services/map-lake/rest/maps/lakeMap";
}

    protected MapView mapView;
    protected LocationManager locationManager;
    protected Location location;
    public static double d_longitude, d_latitude;
    //    public final double offsetX = 18.599785, offsetY = 14.695709;//武汉经纬度与lake偏离量
    public final double offsetX = 0, offsetY = 0;
    Bitmap bitmap_mark;
    public Point2D locationPoint2D;
    //定位信息展示控件
    private View m_DetailLayout;
    private PopupWindow pwDetailInfo;
    private TextView m_textLongitude, m_textLatitude, tv_positionValue;
    // 触屏的x坐标
    private int touchX;
    // 触屏的y坐标
    private int touchY;
    private Point2D longTouchGeoPoint = null;
    private DefaultItemizedOverlay blueMarkerOverlay = null;// 长按标注
    // 输入坐标查询
    private View m_DetailLayout_query;
    private PopupWindow pwDetailInfo_query;
    private TextView m_textfarmCode, m_textfarmDLMC, m_textfarmQSDWMC, m_textfarmZLDWMC;
    private TextView m_textfarmTBMJ, m_textfarmTBDLMJ, m_textfarmXZDWMJ, m_textfarmLXDWMJ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_show);
        //初始界面显示地图
        initMapShow();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!network) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("如需获取更精确的位置服务，请您在室内时执行以下操作:\n 打开WLAN").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
                            Intent myIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).
                    create();
            alertDialog.show();
            String str = "Network没有开!";
            Log.i("WLANmeiyuukai:", str);
        }
        // 从NetWork获取最近的最近的定位信息
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        updateLocation(location);

        // 定位
        Button btn_location = (Button) findViewById(R.id.button_location);
        btn_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLocation();
            }
        });
        //删除overlay
        Button btn_deleteoverlay = (Button) findViewById(R.id.button_deleteoverlay);
        btn_deleteoverlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mapView.removeOverlayByKey("locationOverlay");
            }
        });
        // 打开上传模块
        Button btn_upload = (Button) findViewById(R.id.button_collectLocation);
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapShow.this, UploadPoint.class);
                MapShow.this.startActivity(intent);
            }
        });

        // 回到初始界面
        Button btn_backEntire = (Button) findViewById(R.id.button_back);
        btn_backEntire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mapView.zoomOut();
                mapView.zoomOut();
            }
        });


        // 初始化信息展示控件
        LayoutInflater lfCallOut = getLayoutInflater();
        m_DetailLayout = lfCallOut.inflate(R.layout.detailinfo, null);

        int x = (int)getResources().getDimension(R.dimen.x300);
        int y = (int)getResources().getDimension(R.dimen.y150);
        Log.i("x,y",x+","+y);
        pwDetailInfo = new PopupWindow(m_DetailLayout,x,y);
        m_textLongitude = (TextView) m_DetailLayout.findViewById(R.id.textview_longitude);
        m_textLatitude = (TextView) m_DetailLayout.findViewById(R.id.textview_latitude);
        tv_positionValue = (TextView) m_DetailLayout.findViewById(R.id.textview_farmQSDWMC);
        mapView.getOverlays().add(new TouchOverlay());
        // 初始化用水地信息展示控件
        LayoutInflater lfCallOut_query = getLayoutInflater();
        m_DetailLayout_query = lfCallOut_query.inflate(R.layout.farmlandinfo, null);
        pwDetailInfo_query = new PopupWindow(m_DetailLayout_query, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        m_textfarmDLMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmDLMC);
        m_textfarmCode = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmCode);
        m_textfarmQSDWMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmQSDWMC);
        m_textfarmZLDWMC = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmZLDWMC);
        m_textfarmTBMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmTBMJ);
        m_textfarmTBDLMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmTBDLMJ);
        m_textfarmXZDWMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmXZDWMJ);
        m_textfarmLXDWMJ = (TextView) m_DetailLayout_query.findViewById(R.id.textview_farmLXDWMJ);

    }//onCreate结束

    // 请求位置
    private void requestLocation() {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 1, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateLocation(location);
                drawOnMap();
                locationManager.removeUpdates(this);
                System.out.println("hellooooo3:" + d_longitude + "," + d_latitude);
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateLocation(null);
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 当GPS LocationProvider可用时，更新位置
                updateLocation(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
            }
        });
    }

    // 获取到坐标后，绘图
    private void drawOnMap() {
        if (location != null) {
            Point2D point2D2 = new Point2D(location.getLongitude() + offsetX, location.getLatitude() + offsetY);
            setPoint2DOnMap(point2D2);
            System.out.println("helloooooo" + point2D2.getX() + point2D2.getY());
        } else {
            Toast.makeText(MapShow.this, "不能获取位置服务，请检查", Toast.LENGTH_SHORT).show();
        }
    }


    //初始界面显示地图
    public void initMapShow() {
        mapView = (MapView) this.findViewById(R.id.mapview);
        LayerView layerView = new LayerView(this);
        layerView.setURL(DEFAULT_URL);
        CoordinateReferenceSystem crs = new CoordinateReferenceSystem();
        crs.wkid = 4326;
        layerView.setCRS(crs);
        //设置比例尺数组
        mapView.fixedLevelsEnabled = true;
        double scales[] = {1.0 / 681710.44500652316, 1.0 / 166434.19191046193, 1 / 11437.270579065907};
        layerView.setScales(scales);
        mapView.setClickable(true);
        mapView.setBuiltInZoomControls(true);
        mapView.addLayer(layerView);
        mapView.invalidate();//刷新地图
        mapView.addMapViewEventListener(new MapViewEventAdapter());
    }

    // 更新坐标
    public void updateLocation(Location newLocation) {
        if (newLocation != null) {
            d_longitude = newLocation.getLongitude();
            d_latitude = newLocation.getLatitude();
            System.out.println("hellooooo1:" + d_longitude + "," + d_latitude);
        } else {

        }

    }

    // 地图上标记定位点
    protected void setPoint2DOnMap(Point2D point2D) {
        // 定位到指定点

        //Drawable bitmap_mark = getResources().getDrawable(R.mipmap.min_blue_pin);
        //Point2D point2D = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        setLocationPoint2D(point2D);
        MyOwnOverlay myOwnOverlay = new MyOwnOverlay();
        myOwnOverlay.setKey("locationOverlay");//设置瓦片的key，便于删除
        Log.i("helloooooohhh", myOwnOverlay.getKey());
        mapView.getOverlays().add(myOwnOverlay);
        mapView.invalidate();//添加瓦片之后，及时刷新图层
    }

    class MyOwnOverlay extends Overlay {
        Point2D point2D = getLocationPoint2D();
        //Point2D point2D1 = new Point2D(132.952386, 45.236658);
        //Point2D point2D1 = new Point2D(point2D.getX()+offsetX, point2D.getY()+offsetY);//18.599785 14.695709
        Paint paint = new Paint();

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // 在目标点的位置绘制
            Point point = mapView.getProjection().toPixels(point2D, null);
            bitmap_mark = BitmapFactory.decodeResource(getResources(), R.drawable.min_blue_pin);
            canvas.drawBitmap(bitmap_mark, point.x - bitmap_mark.getWidth() / 2, point.y - bitmap_mark.getHeight() / 2, paint);
            //canvas.drawText("★这里是定位点", point.x, point.y, paint);
        }

        @Override
        public boolean onTap(Point2D point2D, MapView mapView) {
            System.out.println("helloooo" + 123456);
            Point2D point2D_show = new Point2D(getLocation());
            m_textLongitude.setText(Double.toString(point2D_show.getX() + offsetX));
            m_textLatitude.setText(Double.toString(point2D_show.getY() + offsetY));
            Log.i("helloooodingwei:", Double.toString(point2D_show.getX() + offsetX));
//            tv_positionValue.setText(locationName);
            tv_positionValue.setText("待完成");
            //pwDetailInfo.showAtLocation(m_mapControl, Gravity.NO_GRAVITY, 8, 86);
            pwDetailInfo.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置


            m_DetailLayout.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    pwDetailInfo.dismiss();
                }
            });
            return true;
        }

    }

    // 地图上标记定位点
    protected void setLongTouchPoint2DOnMap(Point2D point2D) {
        // 定位到指定点

        //Drawable bitmap_mark = getResources().getDrawable(R.mipmap.min_blue_pin);
        //Point2D point2D = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        setLocationPoint2D(point2D);
        LongTouchOverlay longTouchOverlay = new LongTouchOverlay();
        longTouchOverlay.setKey("locationOverlay");//设置瓦片的key，便于删除
        Log.i("helloooooohhh", longTouchOverlay.getKey());
        mapView.getOverlays().add(longTouchOverlay);
        mapView.invalidate();//添加瓦片之后，及时刷新图层
        Double[] point = Coord.Coord2(point2D.getX(), point2D.getY());
        com.supermap.services.components.commontypes.Point2D point2D1 = new com.supermap.services.components.commontypes.Point2D(point[0], point[1]);
        geometryQuery(point2D1);
    }

    class LongTouchOverlay extends Overlay {
        Point2D point2D = getLocationPoint2D();
        //Point2D point2D1 = new Point2D(132.952386, 45.236658);
        //Point2D point2D1 = new Point2D(point2D.getX()+offsetX, point2D.getY()+offsetY);//18.599785 14.695709
        Paint paint = new Paint();

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // 在目标点的位置绘制
            Point point = mapView.getProjection().toPixels(point2D, null);
            bitmap_mark = BitmapFactory.decodeResource(getResources(), R.drawable.min_blue_pin);
            canvas.drawBitmap(bitmap_mark, point.x - bitmap_mark.getWidth() / 2, point.y - bitmap_mark.getHeight() / 2, paint);
            //canvas.drawText("★这里是定位点", point.x, point.y, paint);
        }

        @Override
        public boolean onTap(Point2D point2D, MapView mapView) {
            System.out.println("helloooo" + 123456);
            Point2D point2D_show = new Point2D(getLocation());

            pwDetailInfo_query.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
            m_DetailLayout_query.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    pwDetailInfo_query.dismiss();
                }
            });
            return true;
        }

    }

    /**
     * 触屏Overlay
     */
    class TouchOverlay extends Overlay {
        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            touchX = Math.round(event.getX());
            touchY = Math.round(event.getY());
            // 记录点击位置
            longTouchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);
            return false;
        }
    }

    /**
     * MapView事件处理适配器，提供长按事件的实现
     */
    class MapViewEventAdapter implements MapView.MapViewEventListener {

        @Override
        public void moveStart(MapView paramMapView) {

        }

        @Override
        public void move(MapView paramMapView) {

        }

        @Override
        public void moveEnd(MapView paramMapView) {

        }

        @Override
        public void touch(MapView paramMapView) {

        }

        @Override
        public void longTouch(MapView paramMapView) {
            System.out.println("helloooolongtouchyou ");
            if (longTouchGeoPoint != null) {
                setLongTouchPoint2DOnMap(longTouchGeoPoint);
            }
        }

        @Override
        public void zoomStart(MapView paramMapView) {

        }

        @Override
        public void zoomEnd(MapView paramMapView) {

        }

        @Override
        public void mapLoaded(MapView paramMapView) {

        }
    }

    public Point2D getLocation() {
        Point2D point2D = new Point2D(location.getLongitude(), location.getLatitude());
        return point2D;
    }

    public void setLocationPoint2D(Point2D point2D) {
        locationPoint2D = point2D;
    }

    public Point2D getLocationPoint2D() {
        return locationPoint2D;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    private void geometryQuery(com.supermap.services.components.commontypes.Point2D point2D) {
        QueryByGeometryParameters p = new QueryByGeometryParameters();
        p.spatialQueryMode = SpatialQueryMode.INTERSECT;// 必设，空间查询模式，默认相交
        // 构建查询几何对象
        Geometry g = new Geometry();
        g.type = GeometryType.POINT;
//        g.points = new Point2D[]{new Point2D(339371.1679559936, 5013867.211060828)};
        g.points = new com.supermap.services.components.commontypes.Point2D[]{point2D};
        g.parts = new int[]{1};
        p.geometry = g;
        FilterParameter fp = new FilterParameter();
        fp.name = "用水地@lake#1";// 必设参数，图层名称格式：数据集名称@数据源别名
        p.filterParameters = new FilterParameter[]{fp};
        QueryByGeometryService qs = new QueryByGeometryService(DEFAULT_URL);
        qs.process(p, new MyQueryLandEventListener());
    }

    private class MyQueryLandEventListener extends QueryEventListener {
        @Override
        public void onQueryStatusChanged(Object o, EventStatus eventStatus) {
            if (o == null) return;
            QueryResult queryResult = (QueryResult) o;
            if (queryResult.quertyResultInfo.recordsets.length == 0) return;
            if (queryResult.quertyResultInfo.recordsets[0].getFeatures().length == 0) return;
            Feature f = queryResult.quertyResultInfo.recordsets[0].getFeature(0);
            String BSM = f.fieldValues[4];
            String DLMC = f.fieldValues[9];
            String QSDWMC = f.fieldValues[12];
            String ZLDWMC = f.fieldValues[14];
            String TBMJ = f.fieldValues[19];
            String TBDLMJ = f.fieldValues[23];
            String XZDWMJ = f.fieldValues[20];
            String LXDWMJ = f.fieldValues[21];
            m_textfarmCode.setText(BSM);
            m_textfarmDLMC.setText(DLMC);
            m_textfarmQSDWMC.setText(QSDWMC);
            m_textfarmZLDWMC.setText(ZLDWMC);
            m_textfarmTBMJ.setText(TBMJ);
            m_textfarmTBDLMJ.setText(TBDLMJ);
            m_textfarmXZDWMJ.setText(XZDWMJ);
            m_textfarmLXDWMJ.setText(LXDWMJ);


        }
    }

    // 距离量算结果
    public void Measure_distance() {
        // 构造查询参数
        MeasureParameters parameters = new MeasureParameters();
        com.supermap.services.components.commontypes.Point2D[] pts = {new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66)};
        parameters.point2Ds = pts;
        MeasureService service = new MeasureService(DEFAULT_URL);
        MyMeasureEventListener listener = new MyMeasureEventListener();
        service.process(parameters, listener, null);
        try {
            listener.waitUntilProcessed();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    // 量算监听器类
    class MyMeasureEventListener extends MeasureService.MeasureEventListener {
        @Override
        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
            // 量算结果
            MeasureResult result = (MeasureResult) sourceObject;
        }
    }


    // 面积量算结果
    public void Measure_Area() {
        // 构造查询参数
        MeasureParameters parameters = new MeasureParameters();
        com.supermap.services.components.commontypes.Point2D[] pts = {new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66), new com.supermap.services.components.commontypes.Point2D(73.88, 12.6), new com.supermap.services.components.commontypes.Point2D(23, 34)};
        parameters.point2Ds = pts;
        MeasureService service = new MeasureService(DEFAULT_URL);
        MyMeasureEventListener2 listener = new MyMeasureEventListener2();
        service.process(parameters, listener, MeasureMode.AREA);
        try {
            listener.waitUntilProcessed();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    // 量算监听器类
    class MyMeasureEventListener2 extends MeasureService.MeasureEventListener {
        @Override
        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
            // 量算结果
            MeasureResult result = (MeasureResult) sourceObject;
        }
    }

    @Override
    protected void onDestroy() {
        mapView.destroy();
        super.onDestroy();
    }


}
